const db = require('../db/index')
const bcryptjs = require('bcryptjs')
const bodyParser = require('body-parser')
const config = require('../config')

const jsonwebtoken = require('jsonwebtoken')
// 登录
exports.login = async(req,res)=>{
      try {
  const sql = 'select * from user where username=?'

  const [result] = await db.query(sql,req.body.username)

   if (result.length === 0 ) {
     return res.cc('账号未注册！')
    }
   const compareResult = bcryptjs.compareSync(req.body.password, result[0].password)
     if (!compareResult) {
      return res.cc('密码错误！')
    }
   const user = {
      ...result[0],
      img_url: '',
      password: '',

   }
   const tokenStr = jsonwebtoken.sign(user, config.jwtSecretKey, { expiresIn: '12h' })
       res.send({
      status: 200,
      message: '登录成功！',
      token: 'Bearer ' + tokenStr,
    })

      } catch (err) {
    console.error('Login error:', err)
    res.cc(err)
  }
}


// 注册
exports.register = async(req,res)=> {
try{
  const sql = 'select username from user where username=?'
  const [result] = await db.query(sql,req.body.username)

  if(result.length > 0) {
    return res.cc('该账号已被占用！')
  }

  const hashedPassword = bcryptjs.hashSync(req.body.password, 10)
     const created_time = new Date()
    const userinfo = {
      username: req.body.username,
      password: hashedPassword,
      created_time,
    }
    const insertsql = 'insert into user set ?'
    const [results] = await db.query(insertsql,userinfo)
    if(results.affectedRows !== 1) return res.cc('插入失败！数据库无影响！')
     res.cc('注册账号成功！',200)
} catch(err){
    console.error('Registration error:', err)
    res.cc(err)
}
   
}


// (电话验证码验证注册登录)
exports.telphoneLoginReg = async(req,res)=>{
  const sql = 'select * from user where telphone=?'
  const [result] = await db.query(sql,req.body.telphone)
  if(result === 0 && req.verificationCode === '8888'){
     const sql = 'insert into user set ?'

     
  }
}

// 忘记密码
exports.forgetPassword = async(req,res)=>{
  
}